﻿using System;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.SessionState;
using Gp.Examples.FullCalendar.Core;
using Gp.Examples.FullCalendar.Core.Repository;
using Gp.Examples.FullCalendar.Infrastructure;

namespace Gp.Examples.FullCalendar.Authentication
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class LiveIdHandler : IHttpHandler, IRequiresSessionState
    {
        protected string RedirUrl = "/default.aspx";
        protected LiveIdLogin.User _liveUser;
        protected User _user;

        // Initialize the WindowsLiveLogin module.
        private static LiveIdLogin wll = new LiveIdLogin(true);

        public void ProcessRequest(HttpContext context)
        {
            var repository = Resolver.Resolve<IUserRepository>();
            var request = context.Request;
            var response = context.Response;
            var server = context.Server;

            _liveUser = wll.ProcessLogin(context.Request.Form);

            if (_liveUser != null)
            {
                _user = repository.GetUserByLiveIdHash(_liveUser.Id);
            }
            else
            {
                FormsAuthentication.SignOut();
            }

            if (context.Request.QueryString["action"] == "logout")
            {
                LogOut(context);
            }
            else if (context.Request.QueryString["action"] == "clearcookie")
            {
                ClearCookie(response);
            }
            else if (request.QueryString["action"] == "login")
            {
                LogIn(context);
            }
            else
            {
                if (_user == null)
                {
                    // Loo kasutaja siin
                    //_user = new User();
                    //_user.UserName = string.Empty;
                    //_user.LiveIdHash = _liveUser.Id;
                    //_user.Email = string.Empty;
                    //repository.Save(_user);

                    //BlogUserProfile.CreateUser(_user.Id, "");
                    //bup = BlogUserProfile.GetUser(_user.Id);
                }
                else
                {
                    context.Session["UserName"] = _user.UserName;
                }

                if (context.Session["UserName"] == null)
                {
                    context.Session["LiveId"] = _liveUser.Id;
                    response.Redirect("/account/register/");
                    response.End();
                }
                else
                {
                    if (_user.Locked)
                    {
                        FormsAuthentication.SignOut();
                        context.Session.Remove("UserName");
                        response.Redirect(string.Format(LiveIdConfig.LockedUrl));
                        response.End();
                    }

                    //var profRep = new UserProfileRepository(SPContext.Current.Web);
                    //var profile = profRep.GetUserProfileById(bup.ItemId);

                    //if (string.IsNullOrEmpty(profile.Email) ||
                    //    string.IsNullOrEmpty(profile.FirstName) ||
                    //    string.IsNullOrEmpty(profile.LastName) ||
                    //    profile.Interests.Count == 0)
                    //{
                    //    Response.Redirect("/editprofile.aspx?ID=" + bup.ItemId + "&msg=missingflds");
                    //    Response.End();
                    //    return;
                    //}

                    if (_liveUser != null && _liveUser.Context.Length > 0)
                    {
                        RedirUrl = _liveUser.Context;
                    }
                    else
                        RedirUrl = "/";

                    var userName = context.Session["UserName"] as string;
                    //FormsAuthentication.Authenticate(userName, _liveUser.Id);
                    FormsAuthentication.SetAuthCookie(userName, _liveUser.UsePersistentCookie); // _user.UsePersistentCookie);                    
                    response.Redirect(RedirUrl);
                    response.End();
                }
            }
        }

        private void LogIn(HttpContext context)
        {
            var request = context.Request;
            var server = context.Server;

            if (request.QueryString["ReturnUrl"] != null)
            {
                RedirUrl = LiveIdConfig.LiveLoginUrl + server.UrlEncode(request.QueryString["ReturnUrl"]);
            }
            else if (request.UrlReferrer != null)
            {
                RedirUrl = LiveIdConfig.LiveLoginUrl + server.UrlEncode(request.UrlReferrer.ToString());
            }
            else
            {
                RedirUrl = LiveIdConfig.LiveLoginUrl + server.UrlEncode("/");
            }

            var response = context.Response;
            response.Redirect(RedirUrl);
            response.End();
        }

        private static void ClearCookie(HttpResponse response)
        {
            response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            string type;
            byte[] content;

            wll.GetClearCookieResponse(out type, out content);

            response.Clear();
            response.ClearHeaders();
            response.ContentType = type;
            response.BinaryWrite(content);
            response.Flush();
            response.End();
        }

        private static void LogOut(HttpContext context)
        {
            var session = context.Session;
            session.Remove("UserId");
            session.Remove("LiveId");

            var response = context.Response;
            if (response.Cookies[FormsAuthentication.FormsCookieName] != null)
                response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddYears(-10);

            FormsAuthentication.SignOut();
            
            session.Abandon();
            response.Redirect("/");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}